package com.ahj.permission;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PermissionUtils {
    private static Map<Integer, String[]> map = new HashMap<>();

    static {
        map.put(0, new String[]{Manifest.permission.WRITE_CALENDAR});
        map.put(1, new String[]{Manifest.permission.CAMERA});
        map.put(2, new String[]{Manifest.permission.READ_CONTACTS});
        map.put(3, new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
        map.put(4, new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
        map.put(5, new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
        map.put(7, new String[]{Manifest.permission.RECORD_AUDIO});
        map.put(8, new String[]{Manifest.permission.CALL_PHONE});
        map.put(11, new String[]{Manifest.permission.BODY_SENSORS});
        map.put(12, new String[]{Manifest.permission.READ_SMS});
        map.put(13, new String[]{Manifest.permission.RECORD_AUDIO});
        map.put(14, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE});
        map.put(15, new String[]{Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS});
    }

    public static String[] getPermissions(List<Integer> list) {
        if (list == null) {
            return new String[0];
        }
        ArrayList<String> listPermission = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String[] per = map.get(list.get(i));
            if (per != null) {
                if (!listPermission.contains(per[0])) {
                    listPermission.addAll(Arrays.asList(per));
                }
            }
        }
        return listPermission.toArray(new String[listPermission.size()]);
    }

    private static Activity activity;

    public static void jumpPermissionPage(Activity activity) {
        PermissionUtils.activity = activity;
        String name = Build.MANUFACTURER;
        switch (name) {
            case "HUAWEI":
                goHuaWeiMainager();
                break;
            case "vivo":
                goVivoMainager();
                break;
            case "OPPO":
                goOppoMainager();
                break;
            case "Coolpad":
                goCoolpadMainager();
                break;
            case "Meizu":
                goMeizuMainager();
                break;
            case "Xiaomi":
                goXiaoMiMainager();
                break;
            case "samsung":
                goSangXinMainager();
                break;
            case "Sony":
                goSonyMainager();
                break;
            case "LG":
                goLGMainager();
                break;
            default:
                goIntentSetting();
                break;
        }
    }

    private static void goLGMainager() {
        try {
            Intent intent = new Intent(activity.getPackageName());
            ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings$AccessLockSummaryActivity");
            intent.setComponent(comp);
            activity.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(activity, "跳转失败", Toast.LENGTH_LONG).show();
            e.printStackTrace();
            goIntentSetting();
        }
    }

    private static void goSonyMainager() {
        try {
            Intent intent = new Intent(activity.getPackageName());
            ComponentName comp = new ComponentName("com.sonymobile.cta", "com.sonymobile.cta.SomcCTAMainActivity");
            intent.setComponent(comp);
            activity.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(activity, "跳转失败", Toast.LENGTH_LONG).show();
            e.printStackTrace();
            goIntentSetting();
        }
    }

    private static void goHuaWeiMainager() {
        try {
            Intent intent = new Intent(activity.getPackageName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");
            intent.setComponent(comp);
            activity.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(activity, "跳转失败", Toast.LENGTH_LONG).show();
            e.printStackTrace();
            goIntentSetting();
        }
    }

    private static String getMiuiVersion() {
        String propName = "ro.miui.ui.version.name";
        String line;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(
                    new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return line;
    }

    private static void goXiaoMiMainager() {
        String rom = getMiuiVersion();
        Intent intent = new Intent();
        if ("V6".equals(rom) || "V7".equals(rom)) {
            intent.setAction("miui.intent.action.APP_PERM_EDITOR");
            intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
            intent.putExtra("extra_pkgname", activity.getPackageName());
        } else if ("V8".equals(rom) || "V9".equals(rom)) {
            intent.setAction("miui.intent.action.APP_PERM_EDITOR");
            intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
            intent.putExtra("extra_pkgname", activity.getPackageName());
        } else {
            goIntentSetting();
        }
        activity.startActivity(intent);
    }

    private static void goMeizuMainager() {
        try {
            Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.putExtra("packageName", activity.getPackageName());
            activity.startActivity(intent);
        } catch (ActivityNotFoundException localActivityNotFoundException) {
            localActivityNotFoundException.printStackTrace();
            goIntentSetting();
        }
    }

    private static void goSangXinMainager() {
        //三星4.3可以直接跳转
        goIntentSetting();
    }

    private static void goIntentSetting() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
        intent.setData(uri);
        try {
            activity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void goOppoMainager() {
        doStartApplicationWithPackageName("com.coloros.safecenter");
    }

    /**
     * doStartApplicationWithPackageName("com.yulong.android.security:remote")
     * 和Intent open = getPackageManager().getLaunchIntentForPackage("com.yulong.android.security:remote");
     * startActivity(open);
     * 本质上没有什么区别，通过Intent open...打开比调用doStartApplicationWithPackageName方法更快，也是android本身提供的方法
     */
    private static void goCoolpadMainager() {
        doStartApplicationWithPackageName("com.yulong.android.security:remote");
      /*  Intent openQQ = getPackageManager().getLaunchIntentForPackage("com.yulong.android.security:remote");
        startActivity(openQQ);*/
    }

    private static void goVivoMainager() {
        doStartApplicationWithPackageName("com.bairenkeji.icaller");
     /*   Intent openQQ = getPackageManager().getLaunchIntentForPackage("com.vivo.securedaemonservice");
        startActivity(openQQ);*/
    }

    /**
     * 此方法在手机各个机型设置中已经失效
     *
     * @return
     */
    private static Intent getAppDetailSettingIntent() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", activity.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", activity.getPackageName());
        }
        return localIntent;
    }

    private static void doStartApplicationWithPackageName(String packagename) {
        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = activity.getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return;
        }
        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);
        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = activity.getPackageManager()
                .queryIntentActivities(resolveIntent, 0);
        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            // packageName参数2 = 参数 packname
            String packageName = resolveinfo.activityInfo.packageName;
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packageName参数2.mainActivityname]
            String className = resolveinfo.activityInfo.name;
            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            // 设置ComponentName参数1:packageName参数2:MainActivity路径
            ComponentName cn = new ComponentName(packageName, className);
            intent.setComponent(cn);
            try {
                activity.startActivity(intent);
            } catch (Exception e) {
                goIntentSetting();
                e.printStackTrace();
            }
        }
    }

    /// Android: 日历
    /// iOS: Calendar (Events)
    private int calendar = 0;
    /// Android: 相机
    /// iOS: Photos (Camera Roll and Camera)
    private int camera = 1;
    /// Android: 联系人
    /// iOS: AddressBook
    private int contacts = 2;
    /// Android: 位置
    /// iOS: CoreLocation (Always and WhenInUse)
    private int location = 3;
    /// Android: 位置
    /// iOS: CoreLocation - Always
    private int locationAlways = 4;
    /// Android: 位置
    /// iOS: CoreLocation - WhenInUse
    private int locationWhenInUse = 5;
    /// Android: None
    /// iOS: MPMediaLibrary
    private int mediaLibrary = 6;
    /// Android: 麦克风
    /// iOS: Microphone
    private int microphone = 7;
    /// Android: 手机权限
    /// iOS: Nothing
    private int phone = 8;
    /// Android: Nothing
    /// iOS: Photos
    private int photos = 9;
    /// Android: Nothing
    /// iOS: Reminders
    private int reminders = 10;
    /// Android: 传感器
    /// iOS: CoreMotion
    private int sensors = 11;
    /// Android: 短信相关
    /// iOS: Nothing
    private int sms = 12;
    /// Android: 麦克风
    /// iOS: Speech
    private int speech = 13;

    /// Android: SD卡
    /// iOS: Nothing
    private int storage = 14;
    /// Android: 电池优化
    private int ignoreBatteryOptimizations = 15;
}
